package com.alibaba.csp.sentinel.demo.zuul.gateway.filter;

import com.alibaba.csp.sentinel.adapter.gateway.zuul.constants.ZuulConstant;
import com.alibaba.csp.sentinel.demo.zuul.gateway.sentinel.HeaderMapRequestWrapper;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * @author GaoZhiqiang
 * @date 2021-03-17 15:20:35
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    @Value("${ipWhitelist}")
    private String[] ipWhitelist;

    @Autowired
    private Environment env;


    @Override
    public String filterType() {
        return ZuulConstant.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("MyZuulFilter");

     /*   RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String ipAddr = getIpAddr(request);

        // 获取真实IP @author Huahui.wu
        ctx.addZuulRequestHeader("userIp", ipAddr);

        System.out.println("ip=" + ipAddr);

        String token = request.getHeader("token");
//        request = modifyHttpServletRequest(request, token);


        HeaderMapRequestWrapper headerMapRequestWrapper = new HeaderMapRequestWrapper(request);

        if (StringUtils.isEmpty(token)) {
            headerMapRequestWrapper.addHeader("no-token", ipAddr);
        } else {
            headerMapRequestWrapper.addHeader("y-token", token);
        }

        ctx.setRequest(headerMapRequestWrapper);*/

        //ip白名单

     /*   String ipWhitelist = JSON.toJSONString(this.ipWhitelist);

        System.out.println("ipWhitelist = " + ipWhitelist);*/

        String ipWhitelist = env.getProperty("ipWhitelist");
        System.out.println("ipWhitelist=" + ipWhitelist);


        return null;
    }

    private HttpServletRequest modifyHttpServletRequest(HttpServletRequest request, String token) {
        //修改request header 删除header字段
        if (StringUtils.isEmpty(token)) {
            request = new HttpServletRequestWrapper(request) {
                private final String token = "token";
                private Set<String> headerNameSet;

                @Override
                public Enumeration<String> getHeaderNames() {
                    if (headerNameSet == null) {
                        // first time this method is called, cache the wrapped request's header names:
                        headerNameSet = new HashSet<>();
                        Enumeration<String> wrappedHeaderNames = super.getHeaderNames();
                        while (wrappedHeaderNames.hasMoreElements()) {
                            String headerName = wrappedHeaderNames.nextElement();
                            if (!token.equalsIgnoreCase(headerName)) {
                                headerNameSet.add(headerName);
                            }
                        }
                    }
                    return Collections.enumeration(headerNameSet);
                }

                @Override
                public Enumeration<String> getHeaders(String name) {
                    if (token.equalsIgnoreCase(name)) {
                        return Collections.<String>emptyEnumeration();
                    }
                    return super.getHeaders(name);
                }

                @Override
                public String getHeader(String name) {
                    if (token.equalsIgnoreCase(name)) {
                        return null;
                    }
                    return super.getHeader(name);
                }
            };

           /* token = request.getHeader("token");
            System.out.println("token 22 = " + token);*/
        }
        return request;
    }


    private static final String UNKNOWN = "unknown";


    private String getIpAddr(HttpServletRequest request) {
        //先从nginx自定义配置获取
        String ip = request.getHeader("user-remote");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("user-proxy");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-real-ip");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
